package com.bnz.user.controller;

import com.bnz.common.entity.R;
import com.bnz.common.utils.PhoneFormatCheckUtils;
import com.bnz.user.entity.User;
import com.bnz.user.service.UserService;

import com.xxl.sso.core.conf.Conf;
import com.xxl.sso.core.user.XxlSsoUser;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
@RefreshScope
@Controller
@RequestMapping
public class UserController {

//	@Value("${user.username}")
//	private String username;
//	@Value("${user.age}")
//	private int age;

//	@Value("${stud.username}")
//	private String username;
//	@Value("${stud.age}")
//	private int age;

	@Value("${server.port}")
	private int port;
	@Autowired
	private UserService userService;

//	@GetMapping("/info")
//	@ResponseBody
//	public R getInfo() {
//		return R.ok().put("username", username).put("age", age);
//	}


	@GetMapping("/user/list")
	@ResponseBody
	public R findAll(){
		return R.ok().put("list",userService.list());
	}

	//查询单个对象
	@GetMapping("/user/{id}")
	@ResponseBody
	public R findById(@PathVariable String id){
		User user = userService.getById(id);
		return R.ok().put("data",user).put("port",port);
	}



	//1. 访问用户注册首页
	@GetMapping({"/", "/register.html"})
	public String register(HttpServletRequest request, Model model) {
//1.1 得到当前登录用户
		XxlSsoUser userInfo = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
		//1.2 将用户名存放到model中，在页面显示
		model.addAttribute("username", userInfo.getUsername());
		return "register";
	}

	//2. 获取手机号发送验证码
	@GetMapping("/user/sendSms/{phone}")
	public String sendCode(@PathVariable String phone) {
		// 2.1 手机号码格式验证，通过了发短信
		if (PhoneFormatCheckUtils.isPhoneLegal(phone)) {
			System.out.println("phone=" + phone);
			userService.sendSms(phone);
		}
		return "register";
	}

	// 3.添加用户
	@PostMapping("/user/add")
	public String addUser(User user,String code) {
		System.out.println("user = " + user);
		//3.1 判断验证码是否合法
		if (userService.isExistCode(user.getPhone(), code)) {
			System.out.println("验证码输入正确并且合法！！user信息：" + user);
			user.setCreated(new Date());
			user.setUpdated(new Date());
			userService.add(user);
		}
		//3.2 跳转到登录视图
		return "login";
	}
}
